#define _CRT_SECURE_NO_WARNINGS 1
#include "BinaryTree.h"

BTNode* BuyNode( BTDataType x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc error");
		exit(-1);
	}
	node->data = x;
	node->left = node->right = NULL;
	return node;
}

void BTDestory(BTNode* root)
{
	if (root == NULL)
		return;
	BTDestory(root->left);
	BTDestory(root->right);
	free(root);
}

void BTPrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}
	printf("%c ", root->data);
	BTPrevOrder(root->left);
	BTPrevOrder(root->right);
}

void BTInOder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}

	BTInOder(root->left);
	printf("%c ", root->data);
	BTInOder(root->right);
}

void BTPostOder(BTNode* root)
{
	if (root == NULL)
	{
		printf("# ");
		return;
	}

	BTPostOder(root->left);
	BTPostOder(root->right);
	printf("%c ", root->data);
}

int BTSize(BTNode* root)
{
	return root == NULL ? 0 : BTSize(root->left) + BTSize(root->right) + 1;
}

int BTLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;
	if (root->left == NULL && root->right == NULL)
		return 1;
	return BTLeafSize(root->left) + BTLeafSize(root->right);
}

int BTLevelKSize(BTNode* root, int k)
{
	assert(k);
	if (k == 1)
	{
		return 1;
	}
	k--;
	return BTLevelKSize(root->left, k) + BTLevelKSize(root->right, k);
}

BTNode* BTFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
		return NULL;
	if (root->data == x)
		return root;
	BTNode* node = BTFind(root->left, x);
	if (node)
		return node;
	BTNode* ret = BTFind(root->right, x);
	if (ret)
		return ret;
	return NULL;
}

void BTLevelOrder(BTNode* root)
{
	Queue q;
	QueueInit(&q);
	if (root)
		QueuePush(&q, root);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		printf("%c ", front->data);
		if (front->left != NULL)
			QueuePush(&q, front->left);
		if (front->right != NULL)
			QueuePush(&q, front->right);
		QueuePop(&q);
	}
	QueueDestroy(&q);
}

int BTComplete(BTNode* root)
{
	Queue q;
	QueueInit(&q);
	if (root)
		QueuePush(&q, root);
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		if (front == NULL)
			break;
		QueuePush(&q, front->left);
		QueuePush(&q, front->right);
		QueuePop(&q);
	}
	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);
		if (front != NULL)
		{
			QueueDestroy(&q);
			return false;
		}
	}
	QueueDestroy(&q);
	return true;
}

BTNode* BTCreate(BTDataType* a, int n, int* pi)
{
	if (a[*pi] == '#')
	{
		(*pi)++;
		return NULL;
	}
	BTNode* root = (BTNode*)malloc(sizeof(BTNode));
	if (root == NULL)
	{
		perror("malloc error");
		exit(-1);
	}
	root->data = a[*pi];
	(*pi)++;
	root->left = BTCreate(a, n, pi);
	root->right = BTCreate(a, n, pi);

	return root;
}